package com.kawa.kemanage.controller;

import com.kawa.kemanage.entity.dto.RegisterDTO;
import com.kawa.kemanage.entity.User;
import com.kawa.kemanage.util.Result;
import com.kawa.kemanage.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping({"/api/auth","/app/auth"})
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private HttpServletRequest request;

    /**
     * 注册功能
     */
    @PostMapping("/register")
    public Result register(@RequestBody RegisterDTO registerDTO){
        if (registerDTO.getUsername() != null && registerDTO.getPassword() != null && registerDTO.getEmail() != null) {
            boolean result = userService.register(registerDTO);
            if (result) {
                return Result.success("注册成功!!!");
            }
        }
        return Result.error("注册功能暂未开放");
    }


    /**
     * 登录功能使用
     *
     * @param username 前端传入的用户名
     * @param password 前端传入的密码
     * @return 返回json格式的token以及状态码
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestParam String username, @RequestParam String password) {
        try {
            //本来可以使用try-catch的,老懒批了
            Map<String, Object> loginInfo = userService.login(username, password);
            return Result.success(loginInfo);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    /**
     * 查询用户列表
     * @param pageNo 页码
     * @return
     */
    @RequestMapping("/queryUserList")
    public Result userList(
            @RequestParam(required = false, defaultValue = "1") Integer pageNo,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Integer filterType,
            @RequestParam(required = false) String userName) {
        try {
            // 从请求头中获取当前用户类型，如果为空则默认为普通用户
            String userTypeHeader = request.getHeader("User-Type");
            Integer currentUserType = userTypeHeader != null ? Integer.parseInt(userTypeHeader) : 1;

            // 如果是人事权限（userType=5），则排除普通用户（传入1）
            Integer excludeUserType = currentUserType == 5 ? 1 : null;
            return Result.success(userService.UserList(pageNo, pageSize, excludeUserType, filterType, userName));
        } catch (NumberFormatException e) {
            return Result.error("用户类型格式错误");
        } catch (Exception e) {
            return Result.error("获取用户列表失败：" + e.getMessage());
        }
    }


    /**
     * 添加用户
     * @param user
     * @return
     */
    @PostMapping("/addUser")
    public Result addUser(@RequestBody User user) {
        boolean result = userService.addUser(user);
        if (result) {
            return Result.success();
        } else {
            return Result.error("添加失败");
        }

    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @RequestMapping("/delete/{id}")
    public Result deleteUser(@PathVariable Integer id) {
        try {
            // 从请求头中获取当前用户类型
            Integer currentUserType = Integer.parseInt(request.getHeader("User-Type"));
            int deleteNum = userService.deleteUser(id, currentUserType);
            if (deleteNum > 0) {
                return Result.success("删除成功");
            }
            return Result.error("删除失败!!!");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新用户信息
     * @param user
     * @return
     */
    @PutMapping("/update")
    public Result updateUser(@RequestBody User user) {
        try {
            // 从请求头中获取当前用户类型
            Integer currentUserType = Integer.parseInt(request.getHeader("User-Type"));
            boolean result = userService.updateUser(user, currentUserType);
            if (result) {
                return Result.success("修改成功");
            } else {
                return Result.error("修改失败");
            }
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取用户类型列表
     * @return
     */
    @GetMapping("/queryUserTypeList")
    public Result queryUserTypeList() {
        return Result.success(userService.queryUserTypeList());
    }


    //获取用户中心的数据
    @RequestMapping("/personalCenter")
    public Result personalCenter(@RequestParam(required = false) Integer id){
        return Result.success(userService.personalCenter(id));
    }

    @PostMapping("/updatePersonal")
    public  Result updatePersonal(@RequestBody User user){
        return  Result.success(userService.updatePersonal(user));
    }

    /**
     * 修改密码
     * @param user
     * @return
     */
    @PostMapping("/updatePassword")
    public Result updatePassword(@RequestBody User user){
        return Result.success(userService.udatePassword(user));
    }

    /**
     * 修改手机号
     * @param user
     * @return
     */
    @PostMapping("/udatePhone")
    public  Result udatePhone(@RequestBody User user){
        return  Result.success(userService.udatePhone(user));
    }


    /**
     * 获取用户关注的人数据
     * @param follower_id
     * @return
     */
    @RequestMapping("/getFollowees/{follower_id}")
    public Result getFollowees(@PathVariable Integer follower_id){
        return  Result.success(userService.getFollowees(follower_id));
    }

    //获取粉丝数据
    @RequestMapping("/getFollower/{followee_id}")
    public  Result getFollower(@PathVariable Integer followee_id){
        return  Result.success(userService.getFollower(followee_id));
    }


    //取消关注
    @PostMapping("/delFollowee/{follow_id}")
    public  Result delFollowee(@PathVariable Integer follow_id){
        if (userService.delFollowee(follow_id)) {
            return  Result.success("取消关注");
        }else {
            return  Result.error("取消失败");
        }
    }
    //关注
    @PostMapping("/addFollowee")
    public  Result addFollowee(@RequestBody User user) {
        if (userService.addFollowee(user)) {
            return Result.success("关注成功");
        } else {
            return Result.error("关注失败");
        }
    }





        /**
         * 这是测试方法，不知道怎么返回结果的可以看一下怎么返回
         *
         * @return
         */
    @GetMapping("/test")
    public Result<Map<String, Object>> test() {
        Map<String, Object> data = new HashMap<>();
        data.put("name", "张三");
        data.put("age", 25);
        return Result.success(data);
    }
}
